/*
 * @Author: 9ilk 3535851673@qq.com
 * @Date: 2024-11-17 10:13:03
 * @LastEditors: 9ilk 3535851673@qq.com
 * @LastEditTime: 2024-11-20 22:41:35
 * @FilePath: /zhuang/thread/mythread.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <thread>
#include <string>
#include <error.h>
#include <errno.h>
#include <string.h>
using namespace std;

class ThreadData
{
public:
    ThreadData()
    {}
    void Init(const string &name, int a, int b)
    { 
        _name = name;
        _a = a;
        _b = b;
    }
    void Excute()
    {
        _reasult =  _a + _b;
    }
    int Reasult()
    {
        return _reasult;
    }
    ~ThreadData()
    {
    }
    string name()
    {
        return _name;
    }
    void Setid(pthread_t tid)
    {
       _tid = tid;
    }
    pthread_t Id()
    {
        return _tid;
    }
    int A()
    {return _a;}

    int B()
    {return _b;}

private:
    string _name;
    int _a;
    int _b;
    int _reasult;
    pthread_t _tid;
};

string ToHex(pthread_t tid) // 十六进制
{
    char buffer[64];
    snprintf(buffer, sizeof(buffer), "0x%lx", tid);
    return buffer;
}

int gval = 100;
void *routine(void *args)
{
    ThreadData *td = static_cast<ThreadData *>(args);
    while (true)
    {
        cout << "我是新线程,我的名字是:" << td->name() << ",my tid is" << ToHex(pthread_self()) << ",全局变量(可修改): " << gval << endl;
        td->Excute();
        sleep(1);
        break;
    }
    return (void*)td;
}

void *routine2(void *args)
{
    string name = static_cast<const char *>(args);
    while (true)
    {
        cout << "我是新线程,我的名字是:" << name << ",my tid is" << ToHex(pthread_self()) << ",全局变量(只检测): " << gval << endl;
        sleep(1);
    }
    return 0;
}
#define NUM 10

int main()
{
    ThreadData td[NUM+1];
    //准备一批未加工的数据
    for(int i = 1 ; i <= NUM ; i++)
    {
        char id[64];
        snprintf(id,sizeof(id),"thread-%d",i);
        td[i].Init(id,i*10,i*20);
    }
    //创建多线程
    for(int i = 1 ; i<= NUM;i++)
    {
        pthread_t tid;
        pthread_create(&tid,nullptr,routine,&td[i]);
        td[i].Setid(tid);
    }
    //等待线程
     for(int i = 1 ; i<= NUM;i++)
     {
       pthread_join(td[i].Id(),nullptr);
     }
     //统计数据
     for(int i = 1 ;i<=NUM;i++)
     {
        printf("td[%d]: %d + %d = %d[%ld]\n",i,td[i].A(),td[i].B(),td[i].Reasult(),td[i].Id());
     }
    return 0;
}

// int main()
// {
//     pthread_t tid1;
//     ThreadData *td1 = new ThreadData("thread-1", 10, 20);
//     pthread_create(&tid1, nullptr, routine1, td1);
//     ThreadData* ret = nullptr;
//     int n = pthread_join(tid1, (void**)&ret);
//     if (n != 0) // 等待失败
//     {
//         cout << "join error" << " error :" << strerror(n) << endl;
//     }
//     cout << "join success,return value: "<< ret->Reasult() << endl;
//     return 0;
// }